import 'dart:io' show Platform;

import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:sample2/components/alert_helper.dart';
import 'package:sample2/helper/app_helper.dart';
import 'package:webview_flutter/webview_flutter.dart';

class WebViewPage extends StatefulWidget {
  const WebViewPage({super.key, this.html, this.url});
  final String? html;
  final String? url;
  @override
  State<StatefulWidget> createState() {
    return WebviewPageState();
  }
}

class WebviewPageState extends State<WebViewPage> {
  
  String url = "${AppHelper.shared.getBkDomainName()}/flutter";
  WebViewController? webViewController;

  @override
  void initState() {
    super.initState();
    if (Platform.isAndroid) WebView.platform = AndroidWebView();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("WebView Sample"),
      ),
      body: Container(
        width: MediaQuery.of(context).size.width,
        height: MediaQuery.of(context).size.height,
        alignment: Alignment.center,
        decoration: const BoxDecoration(color: Colors.white),
        child: ClipRect(
          child: WebView(
            debuggingEnabled: true,
            javascriptMode: JavascriptMode.unrestricted,
            javascriptChannels: {
              //define a channel to be called by html js.
              JavascriptChannel(
                  name: "TestMethod",
                  onMessageReceived: (message) {
                    String result = message.message;
                    AlertHelper.showAlert(context: context, title: result);
                  })
            },
            onPageStarted: (url) {
              EasyLoading.showProgress(0.05);
            },
            onPageFinished: (url) {
              EasyLoading.dismiss();
              //flutter 調用html js
              webViewController!
                  .runJavascriptReturningResult("flutterCallJsMethod('1')")
                  .then((value) {
                // AlertHelper.showAlert(context: context, title: value);
              });
            },
            onProgress: (progress) {
              EasyLoading.showProgress(progress / 100.0);
            },
            onWebResourceError: (error) {
              debugPrint("got error");
            },
            onWebViewCreated: (controller) {
              webViewController = controller;
              webViewController?.loadHtmlString("""
              <!doctype html>
              <html>
              <head>
              <meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1,minimum-scale=1">
              </head>
              <body>
              <h1 id="h1">Test Html sample</h1>
              <Button onClick="flutterCallJsMethod()">Call JS</Button>
              <Button onClick="callFlutter()">Call Flutter</Button>
              <script>
              //
              function flutterCallJsMethod(value){
                if(value !== undefined){
             document.querySelector("#h1").innerText = value;
                }else{
                  document.querySelector("#h1").innerText = parseInt(document.querySelector("#h1").innerText)+1;
                }
                return "haha";
                //alert 彈不出，跟webview_flutter版本有關
              };
              function callFlutter(){
                //call flutter method
                TestMethod.postMessage("a");
              }
              </script>

              </body>
              </html>
          """).then((value) {
                debugPrint("file loaded");
              });
            },
            // initialUrl: url,
            backgroundColor: Colors.red,
          ),
        ),
      ),
    );
  }
}
